<?php

/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 16/4/5
 * Time: 上午10:19
 */
class SendService extends Service{
	
	public static function indexHeader(){
		return array(
				'id'             => array('text' => 'ID', 'rule' => 'int'),
				'server_id'      => array('text' => '服务器'),
				'send_type'      => array('text' => '发送类型'),
				'receive'        => array('text' => '发送对象'),
				'title'          => array('text' => '邮件标题'),
				'content'        => array('text' => '邮件内容','width' => '350px'),
				'item'           => array('text' => '道具'),
				'create_user'       => array('text' => '申请人'),
				'create_time'       => array('text' => '申请时间'),
				'status'            => array('text' => '状态'),
				'action'            => array('text' => '操作')
		);
	}
	

	public static function indexData($params){
		$user = AccAuth::me();
		if($user['IsAdmin'] != 1 && $user['AddBy'] != 1){
			$params['create_user'] = $user['UserID'];
		}
		
		$modSend = new ModSend();
        $result = $modSend->select($params);
    
        $sendType = self::sendType();
        $userList = self::userList();
        $serverList = PubServer::getOptions($platform, $game, 'id');
        $statusList = self::status();
    	foreach($result as &$v){   		
    		$v['content'] = '<div style="white-space:normal;">'.$v['content'].'</div>';
    		$v['server_id'] = $serverList[$v['server_id']];
    		$item_array = json_decode($v['item'],true);
    		$item = '';
    		foreach ($item_array as $key=>$val){
    			if($val['is_bind'] == 1){
    				$bind = '绑定';
    			}
    			if($val['is_bind'] == 0){
    				$bind = '不绑定';
    			}
    			$item .= $val['item_name'].'-'.$val['item_id'].'-'.$val['item_number'].'-'.$bind;
    			$item .= '</br>';
    		}
    		$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
    		$v['item'] = $item;
    		$v['send_type'] = $sendType[$v['send_type']];
    		$v['create_user'] = $userList[$v['create_user']];
    		$status = $v['status'];
    		if($status == 1){
    			$v['status'] = $statusList[$v['status']];
    		}
    		if($status == 2){
    			$v['status'] = '<font color="blue">'.$statusList[$v['status']].'</font>';
    			$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
    		}
    		if($status == 3){
    			$v['status'] = '<font color="red">'.$statusList[$v['status']].'</font>';
    			$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
    		}
    		
    		
    		if($status != 2){
    			//$v['action'] .= ' <a href="'.PubFunc::buildUrl('/oss/?r=send/edit').'&id='.$v['id'].'">编辑</a>';
    		}
    		//$v['action'] .= ' <a href="'.PubFunc::buildUrl('/oss/?r=send/delete').'&id='.$v['id'].'" confirm="是否要删除该条服信息?">删除</a>';
    	}
    	unset($v);
    
    	return $result;
	}
	
	
	public static function approveHeader(){
		return array(
				'id'             => array('text' => 'ID', 'rule' => 'int'),
				'server_id'      => array('text' => '服务器'),
				'send_type'      => array('text' => '发送类型'),
				'receive'        => array('text' => '发送对象'),
				'title'          => array('text' => '邮件标题'),
				'content'        => array('text' => '邮件内容','width' => '350px'),
				'item'           => array('text' => '道具'),
				'create_user'       => array('text' => '申请人'),
				'create_time'       => array('text' => '申请时间'),
				'status'            => array('text' => '状态'),
				'action'            => array('text' => '审核操作')
		);
	}
	
	public static function approveData($params){
		//$params['status'] = 1;
		$modSend = new ModSend();
		$result = $modSend->page($params); 
	
		$sendType = self::sendType();
		$userList = self::userList();
		$serverList = PubServer::getOptions($platform, $game, 'id');
		$statusList = self::status();
		foreach($result['data'] as &$v){
			$v['content'] = '<div style="white-space:normal;">'.$v['content'].'</div>';
			$v['server_id'] = $serverList[$v['server_id']];
			$item_array = json_decode($v['item'],true);
			$item = '';
			foreach ($item_array as $key=>$val){
				if($val['is_bind'] == 1){
					$bind = '绑定';
				}
				if($val['is_bind'] == 0){
					$bind = '不绑定';
				}
				$item .= $val['item_name'].'-'.$val['item_id'].'-'.$val['item_number'].'-'.$bind;
				$item .= '</br>';
			}
			$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
			$v['item'] = $item;
			$v['send_type'] = $sendType[$v['send_type']];
			$v['create_user'] = $userList[$v['create_user']];
			$status = $v['status'];
			if($status == 1){
				$v['status'] = '<span class="xstatus">'.$statusList[$v['status']].'</span>';
				$v['action'] .= '<div class="xaction">';
				$v['action'] .= '<a href="javascript:;" name="approve" data-id="'.$v['id'].'"><font color="blue">批准</font></a>';
				$v['action'] .= '&nbsp;&nbsp;&nbsp;<a href="javascript:;" name="reject" data-id="'.$v['id'].'"><font color="red">驳回</font></a>';
				$v['action'] .= '</div>';
			}
			if($status == 2){
				$v['status'] = '<font color="blue">'.$statusList[$v['status']].'</font>';
				$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
			}
			if($status == 3){
				$v['status'] = '<font color="red">'.$statusList[$v['status']].'</font>';
				$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
			}
			
			$id = $v['id'];
			$checkbox = '<input value="'.$v['id'].'" data-status="'.$v['show_status'].'" data-tmp="'.$v['open_time'].'" data-wlk="'.$v['is_wlk'].'" name="id" type="checkbox">&nbsp;&nbsp;';
			$v['id'] = $checkbox.$v['id'];

			
		}
		unset($v);
	
		return $result;
	}
	
	public static function doAdd($params){
		if(PubFunc::checkEmpty($params, array('server', 'send_type','title','content'))){
			return array('state' => false, 'msg' => '缺少必要参数.');
		}
		$server_array = explode('-', $params['server']);
		$params['server'] = $server_array[0];
		//请求接口，接口成功再入库
		//$result = self::send($params);
		$result['state'] = true;
		if($result['state']){
			$user = AccAuth::me();
			$modSend = new ModSend();
			
			if($params['send_type'] == 1){
				$receive = $params['rolename'];
			}
			
			if($params['send_type'] == 2){
				$receive = $params['roleid'];
			}
			
			if($params['send_type'] == 3){
				$receive = $params['accountname'];
			}
			
			$item = '';
			if($params['is_send_good'] == 2){ //不发送道具
				$item = '';
			}
			
			if($params['is_send_good'] == 1){ //发送道具
				$person_item = array();
			    foreach ($params['item_id'] as $key=>$val){
			    	$data = array();
				    $data['item_name'] = $params['item_name'][$key];
				    $data['item_id'] = $params['item_id'][$key];
				    $data['item_number'] = $params['item_number'][$key];
				    $data['is_bind'] = $params['is_bind'][$key];
				    array_push($person_item, $data);
			    }
			    $item = json_encode($person_item);
			}

			$modSend->platform      = 'test';
			$modSend->game          = $params['g'];
			$modSend->server_id  = $server_array[0];
			$modSend->server_name   = $server_array[1];
			$modSend->send_type    = $params['send_type'];
			$modSend->receive       = $receive;
			$modSend->title       = $params['title'];
			$modSend->content       = $params['content'];
			$modSend->item = $item;
			$modSend->create_user   = $user['UserID'];
			$modSend->create_time   = time();
			$modSend->update_user   = $user['UserID'];
			$modSend->update_time   = time();
			$modSend->status = 1;
			$result = $modSend->save();
			return array('state' => true, 'msg' =>'发送成功');				
		}else{
			return array('state' => false, 'msg' => $result['msg']);
		}
		 
	}
	
	
	public static function delete($id){
		if(empty($id)) return false;
	
		$modSend = new ModSend();
		$modSend->deleteByPk($id);
		return true;
	}

    public static function send($params){
        switch($params['send_type']){
        	case 1:
        		$params['rolename']     = CommonService::getStringFromMultiLine($params['rolename']);
        		$params['roleid']       = '';
        		$params['accountname']  = '';
        		break;
        	case 2:
        		$params['rolename']     = '';
        		$params['roleid']       = CommonService::getStringFromMultiLine($params['roleid']);
        		$params['accountname']  = '';
        		break;
        	case 3:
        		$params['rolename']     = '';
        		$params['roleid']       = '';
        		$params['accountname']  = CommonService::getStringFromMultiLine($params['accountname']);
        		break;
        	default:
        		$params['rolename']     = '';
        		$params['roleid']       = '';
        		$params['accountname']  = '';
        }
           
        $accessory = array();
        foreach($params['item_id'] as $k=>$v){
            if(!empty($v) && !empty($params['item_number'][$k])){
                $accessory['item'][] = array(
                    'type'  => 1,
                    'id'    => $v,
                    'nums'  => intval($params['item_number'][$k]),
                	'name'  => $params['item_name'][$k],
                	'is_bind' => $params['is_bind'][$k],
                );
            }
        }

        unset($params['item_number']);

        $params['attached'] = $accessory;

        $api = new ApiService($params['server']);

        
        $args = array(
            'sendtype'      => $params['send_type'],
            'rolename'      => $params['rolename'],
            'roleid'        => $params['roleid'],
            'accountname'   => $params['accountname'],
            'mailtitle'     => $params['title'],
            'mailcontent'   => $params['content'],
        	'attached'      => $params['attached'],
        );
        $args['attached']   = json_encode($args['attached']);
//         echo "<pre>";
//         var_dump($args);
//         echo "</pre>";exit;
        $result = $api->sendGift($args);
        return $result;
    }

    public static function sendType(){
        return array(
            '1' => '按角色名发送',
            '2' => '按角色ID发送',
            //'3' => '按账号名发送'
        );
    }
    
    public static function status(){
    	return array(
    			'1' => '未批准',
    			'2' => '已批准',
    			'3' => '已驳回',
    	);
    }
    
    /**
     * 批量批准、驳回
     * @param unknown $id
     * @param unknown $status
     * @return multitype:number string
     */
    public static function batchSetStatus($ids,$status){
    	if(empty($ids) || empty($status)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}
    
    	$modSend = new ModSend();
    	$user = AccAuth::me();
    	
    	$game = PubBase::getCurrentGame();
    	$sendList = $modSend->getListForIds($game,$ids);
    	if(count($sendList) == 0){
    		$result = array('status'=>0,'msg'=>'数据不存在','data'=>'');
    		return $result;
    	}
    	
    	$fin_info = '';
    	$new_status_array = array();
    	foreach ($sendList as $key=>$val){
    		$info = $val;
    		$new_status = 2;
    		 
    		$serverList = PubServer::getOptions($platform, $game, 'id');
    		if($status == 2){
    			$sresult = self::sendVer2($info);
    			//$sresult['state'] = true;
    			if($sresult['state']){
    				$new_status = 2;
    				$approval_info = '序号 <font color="red">'.$info['id'].'</font> 的申请批准<br/>发送服务器 <font color="red">'.$serverList[$info['server_id']].' </font>成功<br/>';
    				$fin_info .= $approval_info;
    			}else{  //发送请求失败
    				$new_status = 3;
    				$approval_info = '序号 <font color="red">'.$info['id'].'</font> 的申请批准<br/>发送服务器 <font color="red">'.$serverList[$info['server_id']].' </font>失败，失败原因 <font color="red">'.$sresult['msg'].'</font>,该申请自动驳回<br/>';
    				$fin_info .= $approval_info;
    			}
    		}else if($status == 3){
    			$new_status = 3;
    			$approval_info = '序号 <font color="red">'.$info['id'].'</font> 的申请驳回<br/>';
    			$fin_info .= $approval_info;
    		}
    		 
    		$approval = array();
    		$approval['time'] = date('Y-m-d H:i',time());
    		$approval['user'] = $user['UserID'];
    		$approval['info'] = $approval_info;
    		 
    		$update = array();
    		$update['status'] = $new_status;
    		$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    		$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    		$mresult = $modSend->updateByPk($info['id'], $update);
    		
    		$new_status_array[] = $new_status;
    		 
    	}
    	
    	$result = array('status'=>1,'msg'=>'操作成功，'.$fin_info,'data'=>$new_status_array);
    	return $result;
    }

    /**
     * 批准、驳回
     * @param unknown $id
     * @param unknown $status
     * @return multitype:number string
     */
    public static function setStatus($id,$status){
    	if(empty($id) || empty($status)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}

    	$modSend = new ModSend();
    	$user = AccAuth::me();
    	$obj = $modSend->findByPk($id);
    	
    	if(!$obj){
    		$result = array('status'=>0,'msg'=>'参数错误','data'=>'');
    		return $result;
    		
    	}
    	$info = $obj->getAttributes();
    	
    	
    	//批准时先发送请求接口，请求成功则申请成功，请求失败则驳回
    	$new_status = 2;
    	
    	$serverList = PubServer::getOptions($platform, $game, 'id');
    	if($status == 2){
    		$sresult = self::sendVer2($info);
    		//$sresult['state'] = true;
    		if($sresult['state']){
    			$new_status = 2;
    			$approval_info .= '批准<br/>发送服务器 <font color="red">'.$serverList[$info['server_id']].' </font>成功<br/>';
    		}else{  //发送请求失败
    			$new_status = 3;
    			$approval_info = '批准<br/>发送服务器 <font color="red">'.$serverList[$info['server_id']].' </font>失败，失败原因 <font color="red">'.$sresult['msg'].'</font>,该申请自动驳回<br/>';
    		}
    	}else if($status == 3){
    		$new_status = 3;
    		$approval_info = '驳回';
    	}
    	
    	$approval = array();
    	$approval['time'] = date('Y-m-d H:i',time());
    	$approval['user'] = $user['UserID'];
    	$approval['info'] = $approval_info;
    	
    	$update = array();
    	$update['status'] = $new_status;
    	$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    	$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    	$mresult = $modSend->updateByPk($id, $update);
    	   	
    	if($mresult){
    		$result = array('status'=>1,'msg'=>'操作成功，'.$approval_info,'data'=>$new_status);
    		return $result;
    	}else{
    		$result = array('status'=>0,'msg'=>'操作失败，'.$approval_info,'data'=>'');
    		return $result;
    	}
    	
    }
    
    /**
     * 发送请求发法
     * @param unknown $params
     * @return Ambigous <multitype:, multitype:boolean string , multitype:boolean multitype: unknown , multitype:boolean unknown mixed , multitype:boolean string Ambigous <multitype:string , number, mixed> >
     */
    public static function sendVer2($info){
    	$params = $info;
    	switch($params['send_type']){
    		case 1:
    			$params['rolename']     = CommonService::getStringFromMultiLine($params['receive']);
    			$params['roleid']       = '';
    			$params['accountname']  = '';
    			break;
    		case 2:
    			$params['rolename']     = '';
    			$params['roleid']       = CommonService::getStringFromMultiLine($params['receive']);
    			$params['accountname']  = '';
    			break;
    		case 3:
    			$params['rolename']     = '';
    			$params['roleid']       = '';
    			$params['accountname']  = CommonService::getStringFromMultiLine($params['receive']);
    			break;
    		default:
    			$params['rolename']     = '';
    			$params['roleid']       = '';
    			$params['accountname']  = '';
    	}
    	
    	$params['item'] = json_decode($params['item'],true);
    	$item_array = array();
    	foreach($params['item'] as $k=>$v){
    		$item_array[$k]['type'] = 1;
    		$item_array[$k]['id'] = $v['item_id'];
    		$item_array[$k]['nums'] = $v['item_number'];
    		$item_array[$k]['name'] = $v['item_name'];
    		$item_array[$k]['is_bind'] = $v['is_bind'];
    	}
    	$accessory['item'] = $item_array;
    	$params['attached'] = json_encode($accessory);

    	$api = new ApiService($info['server_id']);
    	$args = array(
    			'sendtype'      => $params['send_type'],
    			'rolename'      => $params['rolename'],
    			'roleid'        => $params['roleid'],
    			'accountname'   => $params['accountname'],
    			'mailtitle'     => $params['title'],
    			'mailcontent'   => $params['content'],
    			'attached'      => $params['attached'],
    	);
    	
    	$result = $api->sendGift($args);
    	return $result;
    }
    
    public static function get($id){
    	$modSend = new ModSend();
    	$obj = $modSend->findByPk($id);
    
    	if($obj){
    		$info = $obj->getAttributes();
    		switch($info['send_type']){
    			case 1:
    				$info['rolename']     = $info['receive'];
    				$info['roleid']       = '';
    				$info['accountname']  = '';
    				break;
    			case 2:
    				$info['rolename']     = '';
    				$info['roleid']       = $info['receive'];
    				$info['accountname']  = '';
    				break;
    			case 3:
    				$info['rolename']     = '';
    				$info['roleid']       = '';
    				$info['accountname']  = $info['receive'];
    				break;
    			default:
    				$info['rolename']     = '';
    				$info['roleid']       = '';
    				$info['accountname']  = '';
    		}
    		
    		$info['item'] = json_decode($info['item'],true);
    		
    		return $info;
    	}else{
    		return false;
    	}
    }
    
    public static function getApproval($id){
    	$modSend = new ModSend();
    	$obj = $modSend->findByPk($id);
    
    	if($obj){
    		$result = array();
    		$info = $obj->getAttributes();
    		if($info['approval_info'] == ''){
    			return $result;
    		}
    		$approval_info_array = explode(';', $info['approval_info']);
    		$userList = self::userList();
    		foreach ($approval_info_array as $key=>$val){
    			$listOne = json_decode($val,true);
    			$listOne['user'] = $userList[$listOne['user']];
    			$result[] = $listOne;
    		}
    		return $result;
    	}else{
    		return false;
    	}
    }


}